<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :title="`${attachName}`"
    :close-on-click-modal="false"
    append-to-body
    class="dialog-sm"
    top="30px"
    width="700px"
  >
    <template v-if="viewMode">
      <attach-item v-for="(p, index) of attachList" :attach-data="p" :key="index"></attach-item>
    </template>
    <div v-else v-loading="saveLoading">
      <!-- <span class="text-warning">重名的文件请先删除后添加，重名的文件不会再次上传</span> -->
      <upload-oss
        class="form-control-ml"
        multiple
        auto-upload
        :listType="accept === 'image/*' ? 'picture-card' : ''"
        ref="upload"
        :file-name="0"
        :accept="accept"
        :dir="uploadURL"
        :before-remove="handleBeforeRemove"
        :on-remove="handleRemove"
        :on-complete="handleComplete"
        :on-error="onError"
        :file-list="fileList"
      ></upload-oss>
    </div>
  </el-dialog>
</template>

<script>
import { arrayFromString } from '@vimi/utils-tool'

import { deleteOss } from '@/common/api/oss'

// import ImgCard from '@/components/ImgCard'
import AttachItem from '@/bank/components/attach/Item'
import { attachAdapter } from '@/bank/components/attach/index'
export default {
  components: {
    // ImgCard,
    AttachItem,
  },
  props: {
    must: {
      type: Boolean,
      default: false,
    },
    attachName: {
      type: String,
      default: '签约现场',
    },
    accept: {
      type: String,
      default: 'image/*',
    },
    parentTag: {
      type: String,
      default: '',
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
    visible: Boolean,
    queryId: String,
    attachData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      tableName: 'datum_customer_attachment',
      fileList: [],
      attachList: [],
      saveLoading: false,
    }
  },

  computed: {
    uploadURL() {
      return `/attachment/loanApprovel/${this.queryId}`
    },
  },

  watch: {
    visible(val) {
      if (val) {
        this.init()
      }
    },
  },

  created() {},
  methods: {
    onError(err) {
      this.$message.error(err?.errorMessage ?? '上传失败')
    },
    init() {
      this.fileList = this.attachData.map(item => {
        return { ...item }
      })
      this.attachList = this.attachData.map(item => {
        return { ...attachAdapter(item) }
      })
    },
    handleBeforeRemove(_file, _fileList) {
      // if (this.must && this.fileList.length < 2) {
      //   this.$message.warning('至少保存一张照片')
      //   return false
      // }
      return new Promise((resolve, reject) => {
        this.$confirm('此操作将永久删除照片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            resolve(true)
          })
          .catch(() => {
            reject(new Error('false'))
          })
      })
    },
    handleRemove(file, fileList) {
      this.$api
        .deleteData(this.$serviceName, this.tableName, file.id)
        .then(() => {
          this.fileList = [...fileList]
        })
        .finally(() => {
          this.$emit('success', true)
        })
      deleteOss(file.url)
    },
    handleComplete(images) {
      if (!images.length) {
        return this.$message.warning('没有要上传的文件！')
      }
      const datas = []
      images.map(image => {
        if (!this.fileList.find(item => item.url === image.url)) {
          datas.push({
            remark: image.name,
            attachment: image.url,
            attachment_type: this.attachName,
            parent_attachment_type: this.parentTag,
            customer_related_id: this.queryId,
            file_type: 1,
          })
        }
      })
      this.addDatas(datas)
    },
    async addDatas(datas) {
      this.saveLoading = true
      const [res] = await this.$utils.promise(this.$api.addBatch('credit', this.tableName, datas))
      this.saveLoading = false
      if (res) {
        this.$message.success('添加附件成功！')
        this.$emit('success', true)
        this.getData()
      } else {
        this.$message.error('添加附件失败，请重试！')
      }
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.fileList = []
      return this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachName,
          },
          { create_time: 'asc' }
        )
        .then(res => {
          const data = res?.data ?? []
          data.forEach(item => {
            const images = arrayFromString(item.attachment).map(img => {
              return {
                url: img,
                id: item.id,
                attachment_type: item.attachment_type,
                remark: item.remark,
                name: item.remark || item.attachment_type,
                attachment: img,
              }
            })
            this.fileList.push(...images)
          })
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped></style>
